﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;

using AesApplication.Models;

namespace AesApplication.Controllers
{
    [Authorize]
    public class HiringManagerController : Controller
    {
        private AesContext db = new AesContext();

        //
        // GET: /HiringManager/
        public ActionResult Index()
        {
            HiringManagerIndexViewModel model = new HiringManagerIndexViewModel
            {
                Departments = db.DepartmentsManagedBy(WebSecurity.CurrentUserId),
            };

            return View(model);
        }


        //
        // GET: /HiringManager/JobGrid/5
        public ActionResult JobGrid(int id)
        {
            Job job = db.Jobs.Find(id);
            if (job == null)
            {
                return HttpNotFound();
            }

            return View(job);
        }

        [HttpPost]
        public ActionResult UpdateGrid(string submit, int[] AppCheckboxes)
        {
            if(AppCheckboxes != null)
            {
                if(submit.ToLower() == "discard")
                {
                    foreach(int appBox in AppCheckboxes)
                    {
                        Application app = db.Applications.Find(appBox);
                        app.Status = ApplicationStatus.HumanRejected;
                    }
                    db.SaveChanges();
                }
                else if(submit.ToLower() == "hire")
                {
                    Application myApp = db.Applications.Find(AppCheckboxes[0]);
                    Job job = db.Jobs.Where(x => x.ID == myApp.JobID).FirstOrDefault();
                    int numCurrentHires = job.Applications.Where(x => x.Status == ApplicationStatus.Hired).Count();

                    if((numCurrentHires + AppCheckboxes.Count() <= job.Quantity) )
                    {
                        foreach (int appBox in AppCheckboxes)
                        {
                            Application app = db.Applications.Find(appBox);
                            app.Status = ApplicationStatus.Hired;
                        }

                        if((numCurrentHires + AppCheckboxes.Count() == job.Quantity))
                        {
                            db.Jobs.Where(x => x.ID == myApp.JobID).FirstOrDefault().Status = JobStatus.Closed;
                            db.SaveChanges();
                        }
                    }
                    else
                    {
                        TempData["Error"] = "You only have " + (job.Quantity-numCurrentHires) + " hire position(s) available.";
                        return RedirectToAction("JobGrid", "HiringManager");
                    }
                }

            }
            return RedirectToAction("Index", "HiringManager");
        }

        [HttpPost]
        public ActionResult UpdateApplication(string submit, string comment, int id, string manager)
        {
            Application app = db.Applications.Find(id);
            Job job = db.Jobs.Where(x => x.ID == app.JobID).FirstOrDefault();

            switch (submit.ToLower())
            {
                case "hire":
                    app.Status = ApplicationStatus.AwaitingHire;
                    app.HiringManager = manager;
                    app.HiringManagerComment = comment;
                    app.Status = ApplicationStatus.Hired;
                    int numCurrentHires = job.Applications.Where(x => x.Status == ApplicationStatus.Hired).Count();
                    if(numCurrentHires == job.Quantity)
                    {
                        job.Status = JobStatus.Closed;
                    }
                    db.SaveChanges();
                    break;
                case "discard":
                    app.Status = ApplicationStatus.HumanRejected;
                    app.HiringManager = manager;
                    app.HiringManagerComment = comment;
                    db.SaveChanges();
                    break;
                case "save":
                    app.HiringManager = manager;
                    app.HiringManagerComment = comment;
                    db.SaveChanges();
                    break;
            }

            return RedirectToAction("JobGrid", "HiringManager", new { id = job.ID });
        }


        //
        // GET: /HiringManager/Application/5
        public ActionResult Application(int id)
        {
            Application app = db.Applications.Find(id);
            if (app == null)
            {
                return HttpNotFound();
            }

            return View(app);
        }

        //
        // GET: /HiringManager/RequestJob/5
        public ActionResult RequestJob(int DeptID)
        {
            // SECURITY CHECK: User should be a manager of this Department.
            Department dept = db.Departments.Find(DeptID);
            if (dept == null)
            {
                return HttpNotFound();
            }
            if (!dept.IsManagedBy(WebSecurity.CurrentUserId))
            {
                return HttpNotFound();
            }

            RequestJobViewModel model = new RequestJobViewModel()
            {
                Questionnaires = db.Questionnaires,
            };

            return View(model);
        }

        //
        // POST: /HiringManager/RequestJob/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RequestJob(int DeptID, RequestJobViewModel model)
        {
            model.Questionnaires = db.Questionnaires; // See above

            // SECURITY CHECK: User should be a manager of this Department.
            Department dept = db.Departments.Find(DeptID);
            if (dept == null)
            {
                return HttpNotFound();
            }
            if (!dept.IsManagedBy(WebSecurity.CurrentUserId))
            {
                return HttpNotFound();
            }

            if (ModelState.IsValid)
            {
                // Fill in data not already given by form, then add Job to database.
                model.Job.Status = JobStatus.AwaitingActivation;
                model.Job.Requester = WebSecurity.CurrentUserName;
                model.Job.RequestDate = System.DateTime.Now;
                model.Job.DepartmentID = DeptID;

                // XXX: If special questionnaire ID 0 is selected, that means
                // no questionnaire (null).
                if (model.Job.QuestionnaireID == 0)
                {
                    // Integer zero will violate foreign key constraint.
                    // Set it to null.
                    model.Job.QuestionnaireID = null;
                }

                db.Jobs.Add(model.Job);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(model);
        }
	}
}